package Frame.screen;

import FCRendering.FCRConstants;
import FCRendering.FCRMaster;
import FCRendering.ImageUtil;
import FCRendering.NpcBundle;
import VWorldGameStudio.*;
import Function.FCMutilPlayCache;
import Function.FCMutilPlayPropulsionCache;
import VWorldGameStudio.events.CaseEvent;

import java.awt.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import static FCRendering.FCRMaster.*;

//非战斗地图，剧情等
public class DefaultMapScreen extends IScreen {
    Font font1;

    private void drawPlayer(Graphics g, FCRMaster fcrMaster, FCPlayerInfo playerInfo) {
        int startY = (int) ((playerInfo.getPlayer1CoorY() + 14.5 - player1.getPlayer1CoorY()) * fcv.getMapPngSize() - player1.getPianYiX() + playerInfo.getPianYiX());
        int startX = (int) ((playerInfo.getPlayer1CoorX() + 8 - player1.getPlayer1CoorX()) * fcv.getMapPngSize() - player1.getPianYiY() + playerInfo.getPianYiY());
        if(playerInfo.getTalkingMsg() != null){
            g.drawImage(ImageUtil.getImage("talkbg"),
                    startY, (int)(startX - 64 * fcv.getProportion()), fcv.getMapPngSize(), fcv.getMapPngSize(), this);
            g.setFont(font1);
            g.setColor(Color.BLACK);
            g.drawString(playerInfo.getTalkingMsg().substring(0,1), (int)(startY + 16 * fcv.getProportion()), (int)(startX - 25 * fcv.getProportion()));
        }
        g.drawImage(charLib.getCharacterOfName(playerInfo.getSelectPlayer())
                        .getActionImage(playerInfo.getActionDir(), playerInfo.getActionNum(), playerInfo.isDeath()),
                startY, startX, fcv.getMapPngSize(), fcv.getMapPngSize(), this);
    }

    private void drawDriverTank(Graphics g, FCRMaster fcrMaster, FCPlayerInfo playerInfo) {
        int startY = (int) ((playerInfo.getPlayer1CoorY() + 14.5 - player1.getPlayer1CoorY()) * fcv.getMapPngSize() - player1.getPianYiX() + playerInfo.getPianYiX());
        int startX = (int) ((playerInfo.getPlayer1CoorX() + 8 - player1.getPlayer1CoorX()) * fcv.getMapPngSize() - player1.getPianYiY() + playerInfo.getPianYiY());
        FCTank tank = tankLib.getTankOfID(playerInfo.getPlayertank1(), playerInfo.getPlayertankHostId());
        if(tank != null) {
            if(playerInfo.getTalkingMsg() != null){
                g.drawImage(ImageUtil.getImage("talkbg"),
                        startY, (int)(startX - 64 * fcv.getProportion()), fcv.getMapPngSize(), fcv.getMapPngSize(), this);
                g.setFont(font1);
                g.setColor(Color.BLACK);
                g.drawString(playerInfo.getTalkingMsg().substring(0,1), (int)(startY + 16 * fcv.getProportion()), (int)(startX - 25 * fcv.getProportion()));
            }
            g.drawImage(tank.getImageOfDirAndActiveNum(playerInfo.getActionDir(), playerInfo.getActionNum()),
                    startY, startX, fcv.getMapPngSize(), fcv.getMapPngSize(), this);
        }
    }

    @Override
    public void dispatchPaintComponent(Graphics g, FCRMaster fcrMaster) {
        g.setColor(Color.white);
        g.fillRect(0, 0, fcrMaster.getWidth(), fcrMaster.getHeight());
        // 渲染地面
        for (int x = -9; x < 10; x++)
            for (int y = -16; y < 17; y++) {
                int xx = x + player1.getPlayer1CoorX(), yy = y + player1.getPlayer1CoorY();
                FCMap fcMap = mapLib.getMapOfName(player1.getMapname());
                if (xx >= 0 && xx < fcMap.getMapWidth() && yy >= 0
                        && yy < fcMap.getMapHeight()) {

                    String blockname = fcMap.getUnplaceNameOfCoor(xx, yy);
                    if (!blockname.equals("v")) {
                        Image[][] unplaceim = blockLib.getBlockOfID(blockname).getBlockImage();
                        for (int i = unplaceim.length - 1; i > -1; i--)
                            for (int j = 0; j < unplaceim[i].length; j++) {
                                g.drawImage(unplaceim[i][j],
                                        (int) ((y + 14.5 + j) * fcv.getMapPngSize() - player1.getPianYiX()),
                                        (int) ((x + 8 - (unplaceim.length - i - 1)) * fcv.getMapPngSize() - player1.getPianYiY()),
                                        fcv.getMapPngSize(), fcv.getMapPngSize(), this);
                            }
                    }
                } else {
                    Image im = mapLib.getMapOfName(player1.getMapname()).getBackgroundImage();
                    g.drawImage(im, (int) ((y + 14.5) * fcv.getMapPngSize() - player1.getPianYiX()),
                            (int) ((x + 8) * fcv.getMapPngSize() - player1.getPianYiY()), fcv.getMapPngSize(), fcv.getMapPngSize(), this);
                }
            }
        // 渲染放置
        for (int x = -9; x < 10; x++)
            for (int y = -16; y < 17; y++) {
                int xx = x + player1.getPlayer1CoorX(), yy = y + player1.getPlayer1CoorY();
                if (xx >= 0 && xx < mapLib.getMapOfName(player1.getMapname()).getMapWidth() && yy >= 0
                        && yy < mapLib.getMapOfName(player1.getMapname()).getMapHeight()) {

//
//                    String blockname = gameSave.getPlaceOfCoor(xx, yy);
//                    if (blockname == null)
                    String blockname = mapLib.getMapOfName(player1.getMapname())
                            .getPlaceNameOfCoor(xx, yy);

                    String mapKey = player1.getMapname() + "*" + xx + "*" + yy;

                    if (gameSave.getOtherEventMaps().containsKey(mapKey)) {
                        //TODO 放置物已经消失的已经销毁
                        continue;
                    }

                    CopyOnWriteArrayList<String> multiOpendoors = FCMutilPlayCache.multiDoors.get(mapKey);
                    if (multiOpendoors != null && multiOpendoors.size() > 0) {
                        //TODO 别的玩家在开门
                        continue;
                    }
                    if (fcrMaster.getOpendoorx() == xx && fcrMaster.getOpendoory() == yy
                            && fcrMaster.isIsplayopendoormusic()) {
                        //TODO 本地在开门
                        continue;
                    }

                    //TODO 这里是指当前不是开门的状态就画出来
                    if (!blockname.equals("v")) {
                        Image[][] placeim = blockLib.getBlockOfID(blockname).getBlockImage();
                        Image im = mapLib.getMapOfName(player1.getMapname())
                                .getBackgroundImage();
                        for (int i = placeim.length - 1; i > -1; i--)
                            for (int j = 0; j < placeim[i].length; j++) {
                                g.drawImage((placeim[i][j] == null) ? im : placeim[i][j],
                                        (int) ((y + 14.5 + j) * fcv.getMapPngSize() - player1.getPianYiX()),
                                        (int) ((x + 8 - (placeim.length - i - 1)) * fcv.getMapPngSize() - player1.getPianYiY()),
                                        fcv.getMapPngSize(), fcv.getMapPngSize(), this);
                                // System.out.println(mapl.getMapOfName(gamesave.getMapNameOfPlayer1()).getEventNameOfCoor(i,
                                // j));
                            }
                    }

                    //判断箱子是开的还是关的
                    if (!mapLib.getMapOfName(player1.getMapname()).getEventNameOfCoor(xx, yy).equals("v")
                            && !mapLib.getMapOfName(player1.getMapname())
                            .getEventNameOfCoor(xx, yy).equals("null")) {
                        // System.out.println(xx+"?"+yy+"="+mapl.getMapOfName(gamesave.getMapNameOfPlayer1()).getEventNameOfCoor(xx,
                        // yy));
                        FCEvent event = eventLib.getEventOfName(mapLib.getMapOfName(player1.getMapname())
                                .getEventNameOfCoor(xx, yy));
                        if(event == null){
                            System.out.println("空的事件 "+mapLib.getMapOfName(player1.getMapname())
                                    .getEventNameOfCoor(xx, yy));
                        }
                        if (event.getType().equals("case")) {
                            CaseEvent caseEvent = (CaseEvent) event;
                            if (caseEvent.getCaseMoney() < 1 && caseEvent.isCaseNull()) {
                                g.drawImage(blockLib.getBlockOfID("XiangZiA2").getBlockImage()[0][0],
                                        (int) ((y + 14.5) * fcv.getMapPngSize() - player1.getPianYiX()),
                                        (int) ((x + 8) * fcv.getMapPngSize() - player1.getPianYiY()), fcv.getMapPngSize(), fcv.getMapPngSize(),
                                        this);
                            }
                        }
                    }
                }
            }

        //TODO 画地图动画第1层
        FCMap fcMap = mapLib.getMapOfName(player1.getMapname());
        int startX = player1.getPlayer1CoorX() - 9;
        int startY = player1.getPlayer1CoorY() - 16;
        if (fcMap != null) {
            Iterator<Map.Entry<String, String>> iterator = fcMap.getMapAnimation().entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                String[] strings = entry.getKey().split("\\*");
                int[] xy = new int[]{Integer.parseInt(strings[0]), Integer.parseInt(strings[1])};
                if (xy[0] >= startX && xy[0] <= (startX + 18)
                        && xy[1] >= startY && xy[1] <= (startY + 32)) {
                    FCMapAnimation animation = mapAnimationLibrary.getMapAnimationByName(entry.getValue());
                    if (animation != null && animation.getVisiable() == 1 && animation.getMapLevel() == 0) {
                        g.drawImage(animation.getAnimationImg(),
                                (int) ((xy[1] + 14.5 - player1.getPlayer1CoorY()) * fcv.getMapPngSize() - player1.getPianYiX()),
                                (int) ((xy[0] + 8 - player1.getPlayer1CoorX()) * fcv.getMapPngSize() - player1.getPianYiY())
                                , animation.getDrawImgSizeW(), animation.getDrawImgSizeH(), this);
                    }
                }
            }
        }
        //TODO 渲染地图原生坦克,本机的坦克================
        HashMap<String, String> maptank = mapLib.getMapOfName(player1.getMapname())
                .getMapTankHashMap();
        for (String coor : maptank.keySet()) {
            if (!gameSave.isTankMoveOfID(maptank.get(coor))) {
                g.drawImage(tankLib.getTankOfIDForPaint(maptank.get(coor), gameSave.HOST_UID)
                                .getImageOfDirAndActiveNum(fcrMaster.getTankDirOfIDNum(1), 0),
                        (int) ((Integer.valueOf(coor.split("\\*")[1]) + 14.5 - player1.getPlayer1CoorY()) * fcv.getMapPngSize() - player1.getPianYiX()),
                        (int) ((Integer.valueOf(coor.split("\\*")[0]) + 8 - player1.getPlayer1CoorX())
                                * fcv.getMapPngSize() - player1.getPianYiY()), fcv.getMapPngSize(), fcv.getMapPngSize(), this);
            }
        }

        // 渲染非剧情npc
        for (int i = 0; i < fcv.getNpcName().size(); i++) {
            if (!fcrMaster.getPlotnpc1().contains(fcv.getNpcName().get(i))) {
                try {
                    NpcBundle npcBundle = fcv.getNpcBundleHashMap().get(fcv.getNpcName().get(i));

                    int my = npcBundle.locationY;
                    int mx = npcBundle.locationX;
                    int xxx = (int) ((my - player1.getPlayer1CoorY()
                            - 0.5) * fcv.getMapPngSize() + fcrMaster.getWidth() / 2 + npcBundle.offSetX - player1.getPianYiX());
                    int yyy = (int) ((mx - player1.getPlayer1CoorX()
                            - 0.5) * fcv.getMapPngSize() + fcrMaster.getHeight() / 2 + npcBundle.offSetY - player1.getPianYiY());

                    if (gameSave.getBattleBossMaps().containsKey(player1.getMapname() + "*" + mx + "*" + my)) {
                        //TODO 表示这里有一个boss,已经被打死了，不要显示了
                        continue;
                    }
                    if (gameSave.getOtherEventMaps().containsKey(player1.getMapname() + "*" + mx + "*" + my)) {
                        //TODO 剧情已经销毁
                        continue;
                    }
                    g.drawImage(charLib.getCharacterOfName(fcv.getNpcName().get(i)).getActionImage(npcBundle.npcDir, npcBundle.actionNum, false),
                            xxx, yyy, fcv.getMapPngSize(), fcv.getMapPngSize(), this);
                } catch (Exception e) {
                }
            }
        }
        // 渲染剧情npc
        for (String name : fcrMaster.getPlotnpc1()) {
            int xxx = (int) ((fcrMaster.getPlotnpc1suozai().get(name)[1] - player1.getPlayer1CoorY() - 0.5) * fcv.getMapPngSize()
                    + fcrMaster.getPlotnpc1pianyi().get(name)[0] - player1.getPianYiX() + fcrMaster.getWidth() / 2);
            int yyy = (int) ((fcrMaster.getPlotnpc1suozai().get(name)[0] - player1.getPlayer1CoorX() - 0.5) * fcv.getMapPngSize()
                    + fcrMaster.getPlotnpc1pianyi().get(name)[1] - player1.getPianYiY() + fcrMaster.getHeight() / 2);
            g.drawImage(charLib.getCharacterOfName(name).getActionImage(fcrMaster.getPlotnpc1face().get(name),
                    fcrMaster.getPlotnpc1active().get(name), false), xxx, yyy, fcv.getMapPngSize(), fcv.getMapPngSize(), this);
        }

        //牵引坦克，已取到的坦克，和别的玩家的坦克都在这里绘图了
        CopyOnWriteArrayList<FCPropulsion> fcPropulsions = FCMutilPlayPropulsionCache.mapToPropulsionMap.get(player1.getMapname());
        if (fcPropulsions != null) {
            for (FCPropulsion propulsion : fcPropulsions) {
                if (propulsion.getVisable() == 1) {
                    if(player1.getMapname().equals("home3") && !propulsion.getPropulsionHostId().equals(gameSave.HOST_UID)){
                        //TODO 在自家的车库只能显示本地的坦克，安全区域
                        continue;
                    }
                    g.drawImage(propulsion.getPropulsionImage(),
                            (int) ((propulsion.getPcoorY() + 14.5 - player1.getPlayer1CoorY()) * fcv.getMapPngSize() - player1.getPianYiX() + propulsion.getPPianYiX()),
                            (int) ((propulsion.getPcoorX() + 8 - player1.getPlayer1CoorX()) * fcv.getMapPngSize() - player1.getPianYiY() + propulsion.getPPianYiY()), fcv.getMapPngSize(),
                            fcv.getMapPngSize(), this);
                }
            }
        }

        //TODO 查看下其他玩家在不在同一个地图，坐标等
        for (FCPlayerInfo playerInfo : FCMutilPlayCache.gamePlayers) {
            if (playerInfo.getMapname().equals(player1.getMapname())) {
                if (playerInfo.getPlayer1CoorX() >= startX && playerInfo.getPlayer1CoorX() <= (startX + 18)
                        && playerInfo.getPlayer1CoorY() >= startY && playerInfo.getPlayer1CoorY() <= (startY + 32)) {
                    FCTank hasTank = tankLib.getTankOfID(playerInfo.getPlayertank1(), playerInfo.getPlayertankHostId());
                    if (hasTank == null) {
                        drawPlayer(g, fcrMaster, playerInfo);
                    } else {
                        drawDriverTank(g, fcrMaster, playerInfo);
                    }
                }
            }
        }


        // 渲染人物
        if (player1.getPlayertank1().equals("null"))// 未驾驶坦克
        {
            int  px = (int) (((fcrMaster.getWidth() - 64 * fcv.getProportion()) / 2));
            int  py = (int) (((fcrMaster.getHeight() - 64 * fcv.getProportion()) / 2));
            if(player1.getTalkingMsg() != null){
                g.drawImage(ImageUtil.getImage("talkbg"),
                        px, (int)(py - 64 * fcv.getProportion()), fcv.getMapPngSize(), fcv.getMapPngSize(), this);
                g.setFont(font1);
                g.setColor(Color.BLACK);
                g.drawString(player1.getTalkingMsg().substring(0,1), (int)(px + 16 * fcv.getProportion()), (int)(py - 25 * fcv.getProportion()));
            }
            g.drawImage(charLib.getCharacterOfName(player1.getSelectPlayer())
                            .getActionImage(player1.getActionDir(), player1.getActionNum(), player1.isDeath()),
                    px,py, fcv.getMapPngSize(), fcv.getMapPngSize(), this);
        } else// 驾驶坦克
        {
            FCTank t = tankLib.getTankOfID(player1.getPlayertank1(), player1.getPlayertankHostId());
            if (t != null) {
                int  px =  (int) (((fcrMaster.getWidth() - 64 * fcv.getProportion()) / 2));
                int  py =  (int) (((fcrMaster.getHeight() - (64 - ((player1.getActionNum() % 2 == 0) ? 4 : 0)) * fcv.getProportion())
                        / 2));
                if(player1.getTalkingMsg() != null){
                    g.drawImage(ImageUtil.getImage("talkbg"),
                            px, (int)(py - 64 * fcv.getProportion()), fcv.getMapPngSize(), fcv.getMapPngSize(), this);
                    g.setFont(font1);
                    g.setColor(Color.BLACK);
                    g.drawString(player1.getTalkingMsg().substring(0,1), (int)(px + 16 * fcv.getProportion()), (int)(py - 25 * fcv.getProportion()));
                }
                g.drawImage(t.getImageOfDirAndActiveNum(player1.getActionDir(), player1.getActionNum()),
                        px,py, fcv.getMapPngSize(), fcv.getMapPngSize(), this);
            }
        }


        //TODO 画地图动画第2层
        if (fcMap != null) {
            Iterator<Map.Entry<String, String>> iterator = fcMap.getMapAnimation().entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                String[] strings = entry.getKey().split("\\*");
                int[] xy = new int[]{Integer.parseInt(strings[0]), Integer.parseInt(strings[1])};
                if (xy[0] >= startX && xy[0] <= (startX + 18)
                        && xy[1] >= startY && xy[1] <= (startY + 32)) {
                    FCMapAnimation animation = mapAnimationLibrary.getMapAnimationByName(entry.getValue());
                    if (animation != null && animation.getVisiable() == 1 && animation.getMapLevel() == 1) {
                        g.drawImage(animation.getAnimationImg(),
                                (int) ((xy[1] + 14.5 - player1.getPlayer1CoorY()) * fcv.getMapPngSize() - player1.getPianYiX()),
                                (int) ((xy[0] + 8 - player1.getPlayer1CoorX()) * fcv.getMapPngSize() - player1.getPianYiY())
                                , animation.getDrawImgSizeW(), animation.getDrawImgSizeH(), this);
                    }
                }
            }

            Iterator<Map.Entry<String, String>> iterator2 = fcMap.getDynamicMapAnimation().entrySet().iterator();
            while (iterator2.hasNext()) {
                Map.Entry<String, String> entry = iterator2.next();
                String[] strings = entry.getValue().split("\\*");
                int[] xy = new int[]{Integer.parseInt(strings[0]), Integer.parseInt(strings[1])};
                if (xy[0] >= startX && xy[0] <= (startX + 18)
                        && xy[1] >= startY && xy[1] <= (startY + 32)) {
                    FCMapAnimation animation = mapAnimationLibrary.getMapAnimationByName(entry.getKey());
                    if (animation != null && animation.getVisiable() == 1/* && animation.getMapLevel() == 1*/) {
                        g.drawImage(animation.getAnimationImg(),
                                (int) ((xy[1] + 14.5 - player1.getPlayer1CoorY()) * fcv.getMapPngSize() - player1.getPianYiX()),
                                (int) ((xy[0] + 8 - player1.getPlayer1CoorX()) * fcv.getMapPngSize() - player1.getPianYiY())
                                , animation.getDrawImgSizeW(), animation.getDrawImgSizeH(), this);
                    }
                }
            }
        }

        //切换Q键图标
        int showQx = (int) ((fcrMaster.getWidth() - 654 * fcv.getProportion()) / 2 - 78 * fcv.getProportion());
        int showQy = (int) (fcrMaster.getHeight() - 78 * fcv.getProportion());
        g.drawImage(ImageUtil.getImage("gameshowplayerq"), showQx, showQy, (int) (78 * fcv.getProportion()), (int) (78 * fcv.getProportion()), this);
        FCPlayerInfo showingP = FCMutilPlayCache.findPlayerByName(gameSave.HOST_UID, fcv.getShowWhosBagItem());
        if (showingP != null) {
            showQx += 16 * fcv.getProportion();
            showQy += 16 * fcv.getProportion();
            g.drawImage(charLib.getCharacterOfName(showingP.getSelectPlayer()).getActionImage(0, 0, showingP.isDeath()),
                    showQx, showQy, (int) (48 * fcv.getProportion()),
                    (int) (48 * fcv.getProportion()), this);
        }
        g.drawImage(ImageUtil.getImage("gamehelp-I"), (int) ((fcrMaster.getWidth() + 654 * fcv.getProportion()) / 2), (int) (showQy - 16 * fcv.getProportion()),
                (int) (78 * fcv.getProportion()), (int) (78 * fcv.getProportion()), this);

        // 渲染黑色幕布(转场的战斗
        if (fcv.isBattle()) {
            g.drawImage(ImageUtil.getImage("battleBG"), 0, fcv.getBattleY(), (int) (2000 * fcv.getProportion()),
                    (int) (1200 * fcv.getProportion()), this);
        }

    }

    @Override
    public void setBounds() {
        font1 = new Font(FCRConstants.FONT_BLACK, 0, (int) (40 * fcv.getProportion()));
    }


}
